package ChatDemo.server.Handler;

import ChatDemo.message.LoginRequestMessage;
import ChatDemo.message.LoginResponseMessage;
import ChatDemo.server.service.UserServiceFactory;
import ChatDemo.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginRequestInboundHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage loginResponseMessagenew;
        if (login){
            SessionFactory.getSession().bind(ctx.channel(),username);
            loginResponseMessagenew=new LoginResponseMessage(true,"success!");
        }else {
            loginResponseMessagenew=new LoginResponseMessage(false,"fail!");
        }
        ctx.writeAndFlush(loginResponseMessagenew);
    }

}
